package org.uiot.protocol.codec

class CodecRule implements CodecTraits {

    /**
     * 编码脚本
     */
    String encodingScript

    /**
     * 解码脚本
     */
    String decodingScript

    /**
     * 十六进制的占位符/无效值/填充值
     */
    String hexPlaceholder

    /**
     * 备注
     */
    String remark

    Date dateCreated
    Date lastUpdated

    static constraints = {
        code(blank: false, unique: true, matches: /[a-zA-Z0-9]+/)
        name(blank: false)
        endian(nullable: false, inList: ENDIAN.values().toList())
        length(nullable: false, min: 1)
        lengthUnit(nullable: false, LengthUnit.values().toList())
        type(nullable: false)
        encodingScript(blank: true)
        decodingScript(blank: true)
        hexPlaceholder(blank: false, matches: /[a-fA-F0-9]+/)
        remark(blank: true)
        dateCreated()
        lastUpdated()
    }

    static mapping = {
        encodingScript type: "text"
        decodingScript type: "text"
        remark type: "text"
    }

    def asType(Class target) {
        if (target == CachedRule) {
            return new CachedRule(
                    code, name, endian, length, lengthUnit, type, encodingScript, decodingScript,
                    hexPlaceholder ? BytesUtils.convertHexStringToByteArray(hexPlaceholder) : null
            )
        }
        throw new ClassCastException("CodecRule cannot be coerced into $target")
    }
}
